package com.lineage.server.clientpackets;

import com.lineage.echo.ClientExecutor;
import com.lineage.server.IdFactory;
import com.lineage.server.datatables.lock.ClanEmblemReading;
import com.lineage.server.datatables.lock.ClanReading;
import com.lineage.server.model.Instance.L1PcInstance;
import com.lineage.server.model.L1Clan;
import com.lineage.server.serverpackets.S_CharReset;
import com.lineage.server.serverpackets.S_Emblem;
import com.lineage.server.serverpackets.S_ServerMessage;
import com.lineage.server.serverpackets.ServerBasePacket;
import com.lineage.server.templates.L1EmblemIcon;
import com.lineage.server.world.World;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class C_EmblemUpload extends ClientBasePacket {
  private static final Log _log = LogFactory.getLog(C_EmblemUpload.class);
  
  public void start(byte[] decrypt, ClientExecutor client) {
    try {
      read(decrypt);
      L1PcInstance pc = client.getActiveChar();
      if (!pc.isGhost() && 
        !pc.isDead() && 
        !pc.isTeleport()) {
        int clan_id = pc.getClanid();
        if (clan_id == 0)
          return; 
        if (pc.getClan().getLeaderId() != pc.getId()) {
          pc.sendPackets((ServerBasePacket)new S_ServerMessage(219));
          return;
        } 
        L1Clan clan = pc.getClan();
        if (clan == null)
          return; 
        byte[] iconByte = readByte();
        L1EmblemIcon emblemIcon = ClanEmblemReading.get().get(clan_id);
        int newemblemid = IdFactory.get().nextId();
        clan.setEmblemId(newemblemid);
        ClanReading.get().updateClan(pc.getClan());
        if (emblemIcon != null) {
          emblemIcon.set_emblemid(newemblemid);
          emblemIcon.set_clanIcon(iconByte);
          emblemIcon.set_update(emblemIcon.get_update() + 1);
          ClanEmblemReading.get().updateClanIcon(emblemIcon);
        } else {
          emblemIcon = ClanEmblemReading.get().storeClanIcon(clan_id, iconByte, newemblemid);
        } 
        World.get().broadcastPacketToAll((ServerBasePacket)new S_Emblem(emblemIcon));
        L1PcInstance[] onlineClanMember;
        int length = (onlineClanMember = clan.getOnlineClanMember()).length;
        int i = 0;
        while (i < length) {
          L1PcInstance clanmember = onlineClanMember[i];
          clanmember.sendPacketsAll((ServerBasePacket)new S_CharReset(clanmember.getId(), clan.getEmblemId()));
          i++;
        } 
        return;
      } 
      return;
    } catch (Exception e) {
      _log.error(e.getLocalizedMessage(), e);
    } finally {
      over();
    } 
  }
  
  public String getType() {
    return getClass().getSimpleName();
  }
}
